# Propeties:
# * title: within 140 words, maybe less?
# * body
# * author(user): author is just a alias of user
# * visited, ding, cai: used for enval the article, can not less the zero.
# * user_id: foreign key to user.

class Article < ActiveRecord::Base
  require 'check_relation'
  include CheckRelation

  TITLE_LENGTH_MIN = 1
  TITLE_LENGTH_MAX = 140
  TITLE_LENGTH_RANGE = TITLE_LENGTH_MIN .. TITLE_LENGTH_MAX

  belongs_to :user
  belongs_to :author,
             :class_name => 'user',
             :foreign_key => 'user_id'

  validates :title,
            :presence => true,
            :length => TITLE_LENGTH_RANGE
  validates_each :visited, :ding, :cai do |record, attr, value|
    record.errors.add attr, "can not less than zero!" if value < 0
  end

  # last posted for all users
  def self.recent limit
    self.find( :all, :order => 'created_at DESC', :limit => limit )
  end

  # most polular articles for all users.
  def self.most_popular limit
    self.find( :all, :order => 'visited DESC', :limit => limit )
  end
end
